<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>水务基础图层展示(矢量瓦片)</title>
    <link rel="stylesheet" href="./css/ol.css" type="text/css"/>
    <link rel="stylesheet" href="./css/ktol3.css" type="text/css"/>
    <link rel="stylesheet" href="./css/mapPop.css" type="text/css"/>
    <link href="./css/widgets.css" rel="stylesheet"/>
    <link href="./css/pretty.css" rel="stylesheet"/>
    <link href="./css/bootstrap3.3.7.min.css" rel="stylesheet"/>
    <script type="text/javascript" src="./js/jquery.min.3.2.1.js"></script>
    <script
            type="text/javascript"
            src="./js/bootstrap3.3.7.min.js"
    ></script>
    <script
            type="text/javascript"
            src="./js/bootstrap-treeview.js"
    ></script>


    <script type="text/javascript" src="./js/ol-debug.js"></script>
    <script
            type="text/javascript"
            src="./js/iclient-ol-es6.js"
    ></script>
    <script type="text/javascript" src="./js/olms.js"></script>
    <script src="./js/fieldConfig.js"></script>
    <link rel="stylesheet" href="./css/bootstrap-table.min.css"/>

    <script src="./js/bootstrap-table.min.js"></script>
    <script src="./js/bootstrap-table-zh-CN.min.js"></script>
    <script src="./js/turf.min.js"></script>
    <script src="./data/vectorTileLayers.js"></script>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background: #fff;
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
        }

        .cesium-viewer .cesium-widget-credits {
            display: none !important;
        }

        .pnl-right {
            position: fixed;
            right: 20px;
            top: 50px;
            width: 315px;
        }

        .pnl-right ul {
            border-bottom: 1px solid #eaeaea;
        }

        .panel-result {
            position: fixed;
            right: 20px;
            top: 215px;
            width: 315px;
        }

        .input-group input {
            height: 100%;
            padding: 7px;
        }

        .margin-top {
            margin-top: 4px;
        }

        .close-btn {
            position: relative;
            float: right;
            cursor: pointer;
        }

        .fixed-table-pagination .pagination-detail,
        .fixed-table-pagination div.pagination {
            margin-top: 0;
            margin-bottom: 2px;
            font-size: 13px;
            padding: 0 8px;
        }

        .fixed-table-pagination .pagination a {
            padding: 6px 11px;
        }

        .fixed-table-pagination div.pagination {
            padding: 0 5px 0 0;
        }

        #toolbar {
            position: absolute;
            margin: 10px;
            top: 0;
            left: 10px;
            height: 80%;
            overflow-y: auto;
            z-index: 100;
            /* width: 280px; */
        }

        #toolbar .list-group-item {
            position: relative;
            display: block;
            padding: unset;
            margin-bottom: -1px;
            background-color: unset;
            border: unset;
        }

        #info .info-content {
            max-height: 240px;
            overflow: auto;
        }

        #menu {
            position: absolute;
            z-index: 2;
            padding: 6px 10px;
            right: 20px;
            top: 10px;
            border-radius: 4px;
            -moz-box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.1);
            -webkit-box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.1);
            box-shadow: 0px 0px 0px 2px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            background: #fff;
        }

        label {
            margin: 0;
            margin-right: 10px;
        }

        .btn-group button {
            padding: 6px 18px;
        }
    </style>
</head>

<body>
<div id="map" style="width: 100%; height: 100%;"></div>
<div id="menu" class="mapboxgl-ctrl">
    <input
            id="image"
            type="radio"
            name="rtoggle"
            value="image"
            checked="checked"
    />影像底图
    <input
            id="dark"
            type="radio"
            name="rtoggle"
            value="dark"
    />矢量黑夜底图
</div>
<div id="toolbar" class="param-container tool-bar">
    <div id="tree1"></div>
</div>
<div id="info" class="ol-popup">
    <a href="#" id="popup-closer" class="ol-popup-closer"></a>
    <div id="info-content" class="pop-info"></div>
</div>
<div class="panel panel-primary pnl-right">
    <ul class="nav nav-pills">
        <li role="presentation" class="active">
            <a href="#stats" role="tab" data-toggle="tab">按类型统计</a>
        </li>
        <li role="presentation">
            <a href="#query" role="tab" data-toggle="tab">要素查询</a>
        </li>
        <li role="presentation">
            <a href="#buffer" role="tab" data-toggle="tab">空间分析</a>
        </li>
    </ul>
    <!-- 面板区 -->
    <div class="tab-content">
        <div role="tabpanel" class="tab-pane active" id="stats">
            <div style="padding: 8px 15px;">
                <div class="input-group" style="margin-top: 5px;">
                    <span class="input-group-addon" id="basic-addon1">关键字</span>
                    <input
                            id="sKeyword"
                            type="text"
                            class="form-control"
                            placeholder="(可为空)"
                            aria-describedby="basic-addon1"
                    />
                </div>
                <input
                        type="button"
                        class="btn btn-default"
                        style="margin: 10px 0;"
                        value="统计"
                        onclick="onClickStatistic()"
                />
            </div>
        </div>
        <div role="tabpanel" class="tab-pane" id="query">
            <div style="padding: 8px 15px;">
                <div class="input-group">
                            <span class="input-group-addon" id="basic-addon1"
                            >要素类型</span
                            >
                    <select class="form-control" id="typeList">
                    </select>
                </div>
                <div class="input-group margin-top">
                    <span class="input-group-addon">关键字</span>
                    <input
                            id="qKeyword"
                            type="text"
                            class="form-control"
                            placeholder="(可为空)"
                            aria-describedby="basic-addon1"
                    />
                </div>
                <input
                        type="button"
                        class="btn btn-default margin-top"
                        value="查询"
                        onclick="onClickQuery()"
                />
            </div>
        </div>
        <div role="tabpanel" class="tab-pane" id="buffer">
            <div style="padding: 8px 15px;">
                <div class="input-group">
                    <span class="input-group-addon">缓冲距离(km)</span>
                    <input
                            id="distance"
                            type="text"
                            class="form-control"
                            placeholder="(单位：km)"
                            value="2"
                            aria-describedby="basic-addon1"
                    />
                </div>
                <div
                        class="btn-group margin-top"
                        role="group"
                        aria-label="..."
                >
                    <button
                            id="drawPoint"
                            value="Point"
                            type="button"
                            class="btn btn-default"
                    >
                        绘点
                    </button>
                    <button
                            id="drawLine"
                            value="LineString"
                            type="button"
                            class="btn btn-default"
                    >
                        绘线
                    </button>
                    <button
                            id="drawPolygon"
                            value="Polygon"
                            type="button"
                            class="btn btn-default"
                    >
                        绘面
                    </button>
                    <button
                            id="clear"
                            value="Clear"
                            type="button"
                            class="btn btn-default"
                    >
                        清除
                    </button>
                </div>
                <input
                        id="bufferback"
                        type="button"
                        class="btn btn-default margin-top"
                        style="display: none;"
                        value="返回上一级"
                        onclick="backtoForward()"
                />
            </div>
        </div>
    </div>
</div>

<div class="panel panel-primary panel-result" style="display: none;">
    <div class="panel-heading">
        结果
        <span class="close-btn" onclick="onClickClose()"> X </span>
    </div>
    <div class="tbStat" style="display: none;">
        <table id="tbStat" class="table"></table>
    </div>
    <div class="tbQuery" style="display: none;">
        <table id="tbQuery" class="table"></table>
    </div>
    <div class="bufferQuery" style="display: none;">
        <table id="bufferQuery" class="table"></table>
    </div>
</div>
<script type="text/javascript">
    const BASE_LAYERS = {
        image:
            'http://192.168.37.161/tilemap_1/rest/services/SZIMAGE/SZAVI201712_20ZW2K/ImageServer/tile/{z}/{y}/{x}',
        dark:
            'http://192.168.37.161/tilemap_1/rest/services/SZMAP/SZMAP_BLUE_ZW2K/MapServer/tile/{z}/{y}/{x}',
    }

    const REQUEST_STAT = 'http://10.230.30.93:8080/web/search/group'
    const REQUEST_QUERY = 'http://10.230.30.93:8080/web/search/list'
    const REQUEST_DETAIL = 'http://10.230.30.93:8080/web/search/getById'
    const REQUEST_BUFFERCOUNT =
        'http://10.230.30.93:8080/web/search/getSpatialCount'
    const REQUEST_BUFFERDATA =
        'http://10.230.30.93:8080/web/search/getSpatialData'

    var defaultData = [
        {
            text: '水务基础图层',
            nodeId: 'basic',
            nodes: [
                {
                    text: '江河湖泊',
                    nodes: JHHP,
                },
                {
                    text: '水利工程',
                    nodes: [
                        ...SLGC,
                        {
                            text: '泵站',
                            nodes: BENGZ,
                        },
                    ],
                },
                {
                    text: '监测站',
                    nodes: [
                        {
                            text: '水文监测站',
                            nodes: [
                                ...SWJCZ,
                                {
                                    text: '水位站',
                                    nodes: SWZ,
                                },
                                {
                                    text: '水文站',
                                    nodes: SWENZ,
                                },
                                // {
                                // 	text: '安全监测站',
                                // 	nodes: AQJCZ
                                // },
                                // {
                                // 	text: '流量站',
                                // 	nodes: LLZ
                                // },
                                // {
                                // 	text: '水情站',
                                // 	nodes: SQZ
                                // },
                                {
                                    text: '水质站',
                                    nodes: SZZ,
                                },
                                // {
                                // 	text: '工况站',
                                // 	nodes: GKZ
                                // }
                            ],
                        },
                        // ...JCZ,
                        {
                            text: '水事影像监视点',
                            nodes: SSYXJSD,
                        },
                    ],
                },
                {
                    text: '其他管理对象',
                    nodes: [
                        ...QTGLDX,
                        {
                            text: '水源地',
                            nodes: SYD,
                        },
                    ],
                },
                {
                    text: '排水设施',
                    nodes: [
                        // {
                        // 	text: '排水管道',
                        // 	nodes: PSGD
                        // },
                        // {
                        // 	text: '排水渠道',
                        // 	nodes: PSQD
                        // },
                        {
                            text: '排水管点',
                            nodes: [
                                ...PSGDIAN,
                                {
                                    text: '调蓄设施',
                                    nodes: DXSS,
                                },
                            ],
                        },
                        {
                            text: '排水面',
                            nodes: PSM,
                        },
                    ],
                },
            ],
        },
    ]

    // 4490坐标系需自定义
    proj4.defs('EPSG:4490', '+proj=longlat +ellps=GRS80 +no_defs')
    var projection = new ol.proj.get('EPSG:4490')
    projection.setExtent([-180, -90, 180, 90])

    // 指定此Arcgis图层的分辨率
    var resolutions = [
        0.001373291015624828,
        0.000686645507812414,
        0.000343322753906207,
        0.0001716613769531035,
        0.00008583068847655175,
        0.000042915344238275876,
        0.000021457672119137938,
        0.000010728836059568969,
        0.0000053644180297844846,
        0.0000026822090148922423,
        0.0000013411045074461211,
    ]
    var matrixIds = []
    for (var z = 0; z < resolutions.length; ++z) {
        matrixIds[z] = z
    }
    var url = BASE_LAYERS.image
    var view = new ol.View({
        projection: projection, //坐标系参数如果不设置，则默认为墨卡托
        resolutions: resolutions, //分辨率层级数组
        center: [114.139825956825, 22.6513875967627],
        zoom: 1,
    })

    var map = new ol.Map({
        layers: [
            new ol.layer.Tile({
                id: 'baseLayer',
                source: new ol.source.XYZ({
                    url: url,
                    projection: projection,
                    tileGrid: new ol.tilegrid.WMTS({
                        origin: [-180, 90],
                        tileSize: 256,
                        resolutions: resolutions,
                        matrixIds: matrixIds,
                    }),
                }),
            }),
        ],
        target: 'map',
        controls: ol.control.defaults({
            attributionOptions: {
                collapsible: false,
            },
        }),
        view: view,
    })

    var currentLayerGroupId = 'image'
    var layerList = document.getElementById('menu')
    var inputs = layerList.getElementsByTagName('input')
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].onclick = switchMapStyle
    }

    // 切换底图类型
    function switchMapStyle(layer) {
        var layerGroupId = layer.target.id
        if (!layerGroupId) return
        let layers = map.getLayers().getArray()
        let findLayer = null
        for (let each of layers) {
            if (each.getProperties()['id'] === 'baseLayer') {
                findLayer = each
            }
        }
        if (findLayer) map.removeLayer(findLayer)
        var url = BASE_LAYERS[layerGroupId]
        var baseLayer = new ol.layer.Tile({
            id: 'baseLayer',
            source: new ol.source.XYZ({
                url: url,
                projection: projection,
                tileGrid: new ol.tilegrid.WMTS({
                    origin: [-180, 90],
                    tileSize: 256,
                    resolutions: resolutions,
                    matrixIds: matrixIds,
                }),
            }),
        })
        map.addLayer(baseLayer)
        baseLayer.setZIndex(0)
        currentLayerGroupId = layerGroupId
    }

    // 挂接弹窗div
    var content = document.getElementById('info-content')
    var overlay = new ol.Overlay({
        element: document.getElementById('info'),
        autoPan: true,
        autoPanAnimation: {
            duration: 250,
        },
    })
    // map绑定popup
    map.addOverlay(overlay)
    // 关闭按钮
    document.getElementById('popup-closer').onclick = function () {
        overlay.setPosition(undefined)
        this.blur()
        return false
    }

    // 加载矢量瓦片图层
    // var currStyle = null
    // var currLayer = null
    function addVectorTileLayer(key, params) {
        let layers = map.getLayers().getArray()
        let findLayer = null
        for (let each of layers) {
            if (each.getProperties()['id'] === key) {
                findLayer = each
            }
        }
        if (findLayer) {
            map.removeLayer(findLayer)
        }

        var vectorLayer = null
        var format = new ol.format.MVT({
            featureClass: ol.Feature,
        })
        var styleURL = params.vtUrl + '/style.json'
        var style = new ol.supermap.MapboxStyles({
            style: styleURL,
            map: map,
        })
        style.on('styleloaded', function () {
            vectorLayer = new ol.layer.VectorTile({
                declutter: true,
                source: new ol.source.VectorTileSuperMapRest({
                    style: styleURL,
                    projection: projection,
                    format: format,
                }),
                style: style.getStyleFunction(),
            })
            vectorLayer.set('id', key)
            map.addLayer(vectorLayer)
            vectorLayer.setZIndex(5)

            // console.log('style', style)
            // console.log('styleSelected', style.selectedStyle())
            // currLayer = vectorLayer
            // currStyle = style
        })
    }

    // 地图点击
    map.on('click', mapOnClickListener)

    function mapOnClickListener(e) {
        // 取消定位
        overlay.setPosition(undefined)
        var selected = false
        // 获取点位要素
        var features = map.getFeaturesAtPixel(e.pixel, {
            hitTolerance: 5, // 容差
        })
        if (!features || !features.length) return
        var props = features[0].getProperties()
        console.log(props)
        let layerKey = '' // 图层名称
        if (props.layer) {
            let sourceArr = props.layer.split('@')
            layerKey = sourceArr[1]
        }
        let html = ''
        // 将主要字段放在前面
        if (props['obj_name']) {
            html = html + '名称：' + props['obj_name'] + '<br>'
        }
        if (props['obj_code']) {
            html = html + '编码：' + props['obj_code'] + '<br>'
        }
        if (props['bas_nm']) {
            html = html + '所属流域：' + props['bas_nm'] + '<br>'
        }
        if (props['bas_cd']) {
            html = html + '流域编码：' + props['bas_cd'] + '<br>'
        }
        let ignoreProps = [
            'center_x',
            'center_y',
            'geometry',
            'layer',
            'fd_type',
            'obj_name',
            'obj_code',
            'elementtype',
            'elementtyp',
            'bas_nm',
            'bas_cd',
            'UserID',
            'Z',
            'elementtyp',
            'elementtype',
            'RefName',
            'Field_smuserid',
            'field_smuserid',
            'name',
            'code',
            'PRJTP',
            'LY_2',
            'x1',
            'x2',
            'y1',
            'y2',
        ]
        for (let prop in props) {
            // 忽略supermap自带字段 与 自定义忽略字段
            if (
                prop.substr(0, 2).toUpperCase() === 'SM' ||
                ignoreProps.includes(prop)
            ) {
                continue
            }
            let propName = getCnField(layerKey, prop)
            html = html + propName + '：' + props[prop] + '<br>'
        }
        content.innerHTML = html
        if (!html) return
        // 指定弹窗位置
        overlay.setPosition(e.coordinate)
        selected = true
    }

    let highLightFeatures = []
    let highLightStyle = new ol.style.Style({
        image: new ol.style.Circle({
            stroke: new ol.style.Stroke({
                color: 'red',
                width: 3,
            }),
        }),
        stroke: new ol.style.Stroke({
            color: 'red',
            width: 3,
        }),
        fill: new ol.style.Fill({
            color: 'rgba(0, 0, 255, 0.1)',
        }),
    })
    var source = new ol.source.Vector({
        wrapX: false,
    })
    var highlightLayer = new ol.layer.Vector({
        source: source,
        style: highLightStyle,
    })
    highlightLayer.setZIndex(99)
    map.addLayer(highlightLayer)
    // 鼠标移上高亮
    var vtStyle = null
    map.on('pointermove', pointermoveFunc)

    function pointermoveFunc(e) {
        source.clear()
        if (e.dragging) return
        map.forEachFeatureAtPixel(
            e.pixel,
            function (feature, featureLayer) {
                if (feature) {
                    // debugger
                    // // console.log(feature.getGeometry())
                    // // console.log(source.getFeatures()[0])
                    source.addFeature(feature)
                    feature.setStyle(highLightStyle)

                    // currStyle.setSelectedId(
                    //     feature.getId(),
                    //     currLayer
                    // )
                    // currStyle.updateStyles([{
                    //     "id": feature.getId(),
                    //     "layout": {
                    //         "line-cap": 'round'
                    //     },
                    //     "paint": {
                    //         "line-width": 10,
                    //         "line-color": '#dd4f42',
                    //         'fill-color': '#627BC1',
                    //     }
                    // }]);
                    // currLayer.getSource().changed()
                    // debugger
                }
            },
            {
                hitTolerance: 1,
            }
        )
    }

    // 改变样式
    // function changeStyle(styleOption) {
    //     currStyle.updateStyles([{
    //         id: 95,
    //         layout: {
    //             'line-cap': 'round'
    //         },
    //         paint: {
    //             'line-width': styleOption.style.lineWidth,
    //             'line-color': styleOption.style.lineColor
    //         }
    //     }])
    //     source.changed()
    // }

    // 获取中文字段名
    function getCnField(key, en) {
        if (!key) return en
        if (!FIELD_CONFIG[key]) return en
        return FIELD_CONFIG[key][en] ? FIELD_CONFIG[key][en] : en
    }

    // 移除图层
    function removeLayer(key) {
        let layers = map.getLayers().getArray()
        let findLayer = null
        for (let each of layers) {
            if (each.getProperties()['id'] === key) {
                findLayer = each
            }
        }
        if (findLayer) {
            map.removeLayer(findLayer)
        }
    }

    var nodeCheckedSilent = false

    function nodeChecked(event, node) {
        if (nodeCheckedSilent) return
        nodeCheckedSilent = true
        addVectorTileLayer(node.nodeId, node)
        checkAllParent(node)
        checkAllSon(node)
        nodeCheckedSilent = false
    }

    var nodeUncheckedSilent = false

    function nodeUnchecked(event, node) {
        if (nodeUncheckedSilent) {
            return
        }
        nodeUncheckedSilent = true
        removeLayer(node.nodeId)
        uncheckAllParent(node)
        uncheckAllSon(node)
        nodeUncheckedSilent = false
    }

    // 选中全部父节点
    function checkAllParent(node) {
        $('#tree1').treeview('checkNode', node.nodeId, {
            silent: true,
        })

        var parentNode = $('#tree1').treeview('getParent', node.nodeId)
        if (!('nodeId' in parentNode)) {
            return
        } else {
            checkAllParent(parentNode)
        }
    }

    //取消全部父节点
    function uncheckAllParent(node) {
        $('#tree1').treeview('uncheckNode', node.nodeId, {
            silent: true,
        })
        var siblings = $('#tree1').treeview('getSiblings', node.nodeId)
        var parentNode = $('#tree1').treeview('getParent', node.nodeId)
        if (!('nodeId' in parentNode)) {
            return
        }
        var isAllUnchecked = true //是否全部没选中
        for (var i in siblings) {
            if (siblings[i].state.checked) {
                isAllUnchecked = false
                break
            }
        }
        if (isAllUnchecked) uncheckAllParent(parentNode)
    }

    // 级联选中所有子节点
    function checkAllSon(node) {
        $('#tree1').treeview('checkNode', node.nodeId, {
            silent: true,
        })
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                addVectorTileLayer(node.nodes[i].nodeId, node.nodes[i])
                checkAllSon(node.nodes[i])
            }
        }
    }

    // 级联取消所有子节点
    function uncheckAllSon(node) {
        if (!node) return
        $('#tree1').treeview('uncheckNode', node.nodeId, {
            silent: true,
        })
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                removeLayer(node.nodes[i].nodeId)
                uncheckAllSon(node.nodes[i])
            }
        }
    }

    $('#tree1').treeview({
        showCheckbox: true,
        data: defaultData,
        onNodeChecked: nodeChecked,
        onNodeUnchecked: nodeUnchecked,
        levels: 3,
    })

    $('#tree1').treeview('uncheckAll', {
        silent: true,
    })

    $('#tbStat').bootstrapTable({
        striped: true, //是否显示行间隔色
        cache: false, //是否使用缓存，默认为true
        smartDisplay: false,
        search: false, //是否显示表格搜索
        strictSearch: true,
        showColumns: false, //是否显示所有的列
        showRefresh: false, //是否显示刷新按钮
        minimumCountColumns: 2, //最少允许的列数
        clickToSelect: true, //是否启用点击选中行
        height: 500, //行高
        uniqueId: 'ID', //每一行的唯一标识
        showToggle: false, //是否显示详细视图和列表视图的切换按钮
        cardView: false, //是否显示详细视图
        detailView: false, //是否显示父子表
        columns: [
            {
                field: 'obj_type_name',
                title: '名称',
                width: 180,
            },
            {
                field: 'count',
                title: '数量',
                width: 120,
            },
        ], //列设置
        onClickRow: function (row, $element) {
            if (bufferWKT && row.obj_type) {
                $('#bufferback')[0].style.display = 'block'
                getItemList(row.obj_type)
            }
        },
    })

    // 统计
    function onClickStatistic() {
        clearInteraction()
        $('.panel-result')[0].style.display = 'block'
        $('.tbStat')[0].style.display = 'block'
        $('.tbQuery')[0].style.display = 'none'

        // 请求参数
        var jsonParam = JSON.stringify({
            keyword: $('#sKeyword')[0].value,
        })
        $.ajax({
            url: REQUEST_STAT,
            data: jsonParam,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                if (res.data) {
                    var result = {
                        data: res.data.groups,
                        total: res.data.groups.length,
                    }
                    $('#tbStat').bootstrapTable('load', result)
                }
            },
        })
    }

    loadSelector()

    // 加载所有类型
    function loadSelector() {
        // 请求所有类型
        var jsonParam = JSON.stringify({
            keyword: '',
        })
        $.ajax({
            url: REQUEST_STAT,
            data: jsonParam,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                if (res.data) {
                    var opts = res.data.groups
                    var html = ''
                    for (let each of opts) {
                        html +=
                            '<option value="' +
                            each.obj_type +
                            '">' +
                            each.obj_type_name +
                            '</option>'
                    }
                    $('#typeList').append(html)
                }
            },
        })
    }

    // 初始化表格
    $('#tbQuery').bootstrapTable({
        striped: true, //是否显示行间隔色
        // cache: false, //是否使用缓存，默认为true
        smartDisplay: false,
        search: false, //是否显示表格搜索
        strictSearch: true,
        showColumns: false, //是否显示所有的列
        showRefresh: false, //是否显示刷新按钮
        minimumCountColumns: 2, //最少允许的列数
        clickToSelect: true, //是否启用点击选中行
        height: 535, //行高
        uniqueId: 'ID', //每一行的唯一标识，一般为主键列
        showToggle: false, //是否显示详细视图和列表视图的切换按钮
        cardView: false, //是否显示详细视图
        detailView: false, //是否显示父子表
        pageNumber: 1, //初始化加载第一页
        pagination: true, //是否分页
        pageSize: 20, //单页记录数
        onClickRow: rowClick,
        onPageChange: pageChanged,
        columns: [
            {
                field: 'obj_code',
                title: '编码',
                width: 80,
            },
            {
                field: 'obj_name',
                title: '名称',
                width: 180,
            },
        ],
    })

    var queryData = []
    var currData = []

    // 页码切换
    function pageChanged(pageNum) {
        overlay.setPosition(undefined)
        if (bufferWKT) {
            var size = $('#tbQuery')[0].rows.length - 1
            let copyData = queryData.slice()
            currData = copyData.splice((pageNum - 1) * size, size)
            AddMapPoints(currData)
        } else {
            var size = $('#tbQuery')[0].rows.length - 1
            let copyData = queryData.slice()
            currData = copyData.splice((pageNum - 1) * size, size)
            AddMapPoints(currData)
        }
    }

    function showDetail(obj) {
        overlay.setPosition(undefined)
        var props = obj
        content.innerHTML =
            '编号：' +
            props['obj_code'] +
            '<br>' +
            '名称：' +
            props['obj_name'] +
            '<br>' +
            '类型：' +
            props['obj_type_name'] +
            '<br>' +
            '经度：' +
            props['center_x'] +
            '<br>' +
            '纬度：' +
            props['center_y']
        overlay.setPosition([
            parseFloat(props['center_x']),
            parseFloat(props['center_y']),
        ])
    }

    function getDetail(id) {
        var jsonParam = JSON.stringify({
            id: id,
        })
        $.ajax({
            url: REQUEST_DETAIL,
            data: jsonParam,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                if (res.data) {
                    showDetail(res.data.item)
                }
            },
        })
    }

    // 行点击
    function rowClick(row, $element, field) {
        // 查询详情并定位
        getDetail(row.id)
        // 定位
        view.setCenter([
            parseFloat(row['center_x']),
            parseFloat(row['center_y']),
        ])
        view.setZoom(6)
    }

    // 查询按钮
    function onClickQuery() {
        clearInteraction()
        $('.panel-result')[0].style.display = 'block'
        $('.tbStat')[0].style.display = 'none'
        $('.tbQuery')[0].style.display = 'block'
        var type = $('#typeList')[0].value
        var keyword = $('#qKeyword')[0].value
        if (!type) return
        // 请求参数
        var jsonParam = JSON.stringify({
            pageIndex: 1,
            pageSize: 1000,
            objType: type,
            keyword: keyword,
        })
        $.ajax({
            url: REQUEST_QUERY,
            data: jsonParam,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                if (res.data) {
                    queryData = res.data.item
                    var result = {
                        data: queryData,
                        total: res.data.item.length,
                    }
                    $('#tbQuery').bootstrapTable('load', result)
                    pageChanged(1)
                }
            },
        })
    }

    var markerLayer = null

    function AddMapPoints(data) {
        var features = []
        for (let each of data) {
            features.push({
                type: 'Feature',
                properties: each,
                geometry: {
                    type: 'Point',
                    coordinates: [
                        parseFloat(each.center_x),
                        parseFloat(each.center_y),
                    ],
                },
            })
        }

        var vectorSource = new ol.source.Vector({
            features: new ol.format.GeoJSON().readFeatures({
                type: 'FeatureCollection',
                features: features,
            }),
            wrapX: false,
        })
        if (markerLayer) {
            markerLayer.setSource(vectorSource)
        } else {
            markerLayer = new ol.layer.Vector({
                source: vectorSource,
                style: new ol.style.Style({
                    image: new ol.style.Icon({
                        anchor: [0.5, 0.5],
                        src: 'img/markerbig_select.png',
                    }),
                }),
            })
            map.addLayer(markerLayer)
            markerLayer.set('id', 'markerLayer')
        }
        var extent = markerLayer.getSource().getExtent()
        view.fit(extent, map.getSize())
    }

    function onClickClose() {
        $('.panel-result')[0].style.display = 'none'
        $('#bufferback')[0].style.display = 'none'
        $('#tbStat').bootstrapTable('load', {
            data: [],
            total: 0,
        })
        overlay.setPosition(undefined)
        $('#tbQuery').bootstrapTable('load', {
            data: [],
            total: 0,
        })
        removeLayer('markerLayer')
        markerLayer = null
    }

    var sourceDraw = new ol.source.Vector({
        wrapX: false,
    })
    var layerDraw = new ol.layer.Vector({
        source: sourceDraw,
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'rgba(0, 153, 255, 0.8)',
                lineDash: [2, 4],
                width: 2,
            }),
        }),
    })
    var sourceBuffer = new ol.source.Vector({
        wrapX: false,
    })
    var layerBuffer = new ol.layer.Vector({
        source: sourceBuffer,
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#6CBBFF',
                width: 3,
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0, 0, 255, 0.1)',
            }),
        }),
    })
    map.addLayer(layerDraw)
    map.addLayer(layerBuffer)

    var buttons = $('.btn-group').children()
    var draw = null
    buttons.map(function (key) {
        var value = buttons[key].value
        if (value === 'Clear') {
            $(buttons[key]).on('click', function () {
                clearInteraction()
            })
            return
        }
        $(buttons[key]).on('click', function () {
            clearInteraction()
            draw = new ol.interaction.Draw({
                source: sourceDraw,
                type: buttons[key].value,
                snapTolerance: 20,
            })
            map.addInteraction(draw)
            draw.on('drawend', featureDrawEnd)
        })
    })

    var drawFeature = null
    var bufferWKT = null

    function featureDrawEnd(event) {
        // 移除交互
        clearInteraction()
        // 存储当前绘制的对象
        drawFeature = event.feature
        let bufferDistance = $('#distance')[0].value
        if (!bufferDistance) {
            bufferDistance = bufferDistance + 0.001
        }
        bufferWKT = startBufferHandler(drawFeature, bufferDistance)
        requestList(bufferWKT)
    }

    function startBufferHandler(feature, distance) {
        let polygonGeometry = null
        bufferArea = buildBuffer(feature, distance)
        sourceBuffer.clear()
        sourceBuffer.addFeature(bufferArea)
        // 转换为WKT格式
        polygonGeometry = bufferArea.getGeometry()
        let format = new ol.format.WKT()
        let wkt = format.writeGeometry(polygonGeometry)
        return wkt
    }

    function requestList(wkt) {
        if (!wkt) return
        let checkedNodes = $('#tree1').treeview('getChecked')
        let types = []
        for (let each of checkedNodes) {
            if (!each.state.expanded) {
                types.push(each.layer)
            }
        }

        onClickClose()
        $('.panel-result')[0].style.display = 'block'
        $('.tbStat')[0].style.display = 'block'
        $('.tbQuery')[0].style.display = 'none'
        var jsonParam = JSON.stringify({
            location: wkt,
            objTypes: types,
        })
        $.ajax({
            url: REQUEST_BUFFERCOUNT,
            data: jsonParam,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                if (res.data) {
                    console.log(res.data)
                    if (res.data.groups) {
                        $('#tbStat').bootstrapTable(
                            'load',
                            res.data.groups
                        )
                    }
                }
            },
        })
    }

    function getItemList(type) {
        $('.panel-result')[0].style.display = 'block'
        $('.tbStat')[0].style.display = 'none'
        $('.tbQuery')[0].style.display = 'block'

        // 请求参数
        var jsonParam = JSON.stringify({
            pageIndex: 1,
            pageSize: 200000,
            location: bufferWKT,
            objType: type,
        })
        $.ajax({
            url: REQUEST_BUFFERDATA,
            data: jsonParam,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                if (res.data) {
                    queryData = res.data.item
                    var result = {
                        data: queryData,
                        total: res.data.total,
                    }
                    $('#tbQuery').bootstrapTable('load', result)
                    pageChanged(1)
                }
            },
        })
    }

    let buildBuffer = function (feature, radius, options, num) {
        let format_ = new ol.format.GeoJSON()
        let geojson = null
        if (num) {
            geojson = feature.features[0]
        } else {
            geojson = format_.writeFeatureObject(feature)
        }
        let result
        try {
            result = turf.buffer(geojson, Number(radius), options)
        } catch (error) {
            console.log(error)
            let simple = turf.simplify(geojson)
            result = turf.buffer(simple, Number(radius), options)
        }
        let resultFeature = null
        if (result) {
            if (result.type === 'Feature') {
                resultFeature = format_.readFeatureFromObject(result)
            } else if (result.type === 'FeatureCollection') {
                resultFeature = format_.readFeaturesFromObject(result)
            }
        }
        return resultFeature
    }

    function backtoForward() {
        $('#bufferback')[0].style.display = 'none'
        $('.panel-result')[0].style.display = 'block'
        $('.tbStat')[0].style.display = 'block'
        $('.tbQuery')[0].style.display = 'none'
        removeLayer('markerLayer')
        markerLayer = null
    }

    function clearInteraction() {
        sourceDraw.clear()
        sourceBuffer.clear()
        bufferWKT = null
        if (draw) {
            map.removeInteraction(draw)
            draw = null
        }
        onClickClose()
    }
</script>
</body>
</html>
